package com.example.userspringboot.service;

import com.example.userspringboot.entity.DrugDetails;
import com.example.userspringboot.entity.Order;
import com.example.userspringboot.exception.CustomerException;
import com.example.userspringboot.mapper.DrugDetailsMapper;
import com.example.userspringboot.mapper.OrderMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class OrderService {

    @Resource
    OrderMapper orderMapper;
    @Resource
    DrugDetailsMapper drugDetailsMapper;

    public void createOrder(Order order,DrugDetails drugDetails) {
        // 生成订单号
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        order.setNumber(now.format(formatter));
        order.setTime(now.format(timeFormatter));
        order.setPrice(drugDetails.getPrice().multiply(new BigDecimal(order.getAmount())));
        orderMapper.createOrder(order);

        DrugDetails dbDrugDetails = drugDetailsMapper.selectById(drugDetails.getId());
        if (dbDrugDetails == null) {
            throw new CustomerException("商品不存在");
        }
        if (dbDrugDetails.getNumber() < order.getAmount()) {
            throw new CustomerException("商品库存不足");
        }
        dbDrugDetails.setNumber(dbDrugDetails.getNumber() - order.getAmount());
        drugDetailsMapper.updateById(dbDrugDetails);
    }

    public List<Order> getOrderById(Integer userId) {
        return orderMapper.getOrderById(userId);
    }
}
